# -*- coding: utf-8 -*-
import os

from django.db import models
from django.contrib.sites.models import Site
from django.core.exceptions import ObjectDoesNotExist
from cmsdj.settings import  DEFAULT_TMP_DIR,\
    TEMPLATES_INSTALL_DIR
from cmsdj.util.keywords import get_keywords_text

def get_template_names_available():
    templates_list = []
    for directory_name in os.listdir( TEMPLATES_INSTALL_DIR ):
        directory = os.path.join(TEMPLATES_INSTALL_DIR, directory_name).replace('\\','/')
        if (os.path.isdir(directory) and directory_name <> '.svn'):
            templates_list.append( (directory,directory_name) )
    return templates_list
    
class SocialCfg (models.Model):
    TAG_SRC_URL = '{{src_url}}'
    TAG_DESCRIPTION = '{{description}}'
    TAG_SUMMARY = '{{summary}}'
    TAG_URL = '{{url}}'
    TAG_AUTHOR = '{{author}}'
    TAG_TITLE = '{{title}}'
    TYPES = (
             (
              'https://twitter.com/intent/tweet?original_referer='+TAG_SRC_URL+'&text='+TAG_TITLE+'&url='+TAG_URL+'&via='+TAG_AUTHOR,
              'twitter',
             ),
             (
              'http://www.facebook.com/sharer/sharer.php?u='+TAG_URL+'&t='+TAG_TITLE,
              'facebook', 
             ),
             (
              'https://plusone.google.com/_/+1/confirm?hl=en&url='+TAG_URL+'&title='+TAG_TITLE,
              'gplus', 
              ),
             (
              'http://www.linkedin.com/shareArticle?mini=true&url='+TAG_URL+'&title='+TAG_TITLE+'&ro=false&summary='+TAG_SUMMARY+'&source='+TAG_SRC_URL,
              'linkedin', 
              ),
             )
    name = models.CharField ( choices = TYPES, max_length = 256 )
#    url = models.URLField ( )
    num_tags = models.PositiveSmallIntegerField ( default=0 )
    author = models.CharField ( max_length=32 )
    img = models.URLField ()
    
    def __unicode__(self):
        return str (self.name)
    
    def get_html (self, content):
        share_url = str( self.name )
        share_url = share_url.replace(self.TAG_TITLE, content.title + " " +content.get_keywords_tags( self.num_tags ))
        share_url = share_url.replace(self.TAG_SRC_URL, content.get_full_url())
        share_url = share_url.replace(self.TAG_DESCRIPTION, content.description)
        share_url = share_url.replace(self.TAG_SUMMARY, content.title + " " +content.get_keywords_tags( self.num_tags ))
        share_url = share_url.replace(self.TAG_URL, content.get_full_url())
        share_url = share_url.replace(self.TAG_AUTHOR, self.author)
        return share_url
        


class BackupCfg (models.Model):
    enabled = models.BooleanField (default = False, help_text = 'Activación de la realización de backups del site')
    defpath = DEFAULT_TMP_DIR+'/tmp'
    path = models.CharField (default = defpath, max_length = 1024 ,help_text = 'Ruta donde se guardarán los backups (def = '+defpath+')')
    periodicity = models.IntegerField (default = 7, help_text = 'Periodicidad con la que se realizan los backups (en días)')
    
    def __unicode__(self):
        return u'Backup en %s cada %s días (%s)' % (self.path, self.periodicity, self.enabled)
    
class ImgCfg (models.Model):
    w = models.PositiveSmallIntegerField( default='100', blank=False, help_text='Ancho en píxeles de la imágen')
    h = models.PositiveSmallIntegerField( default='100', blank=False, help_text='Alto en píxeles de la imágen')
    
    def __unicode__(self):
        return u'%sx%s px' % ( self.w, self.h )

#class CategoryCfg (models.Model):
#    img = models.ForeignKey( ImgCfg )
    
class SiteCfg (models.Model):
    title = models.CharField ( max_length = 256 )
    subtitle = models.CharField ( max_length = 256 , blank=True, null=True)
    abstract = models.TextField ( blank=True, null=True )
    footinfo = models.TextField ( blank=True, null=True )
    site = models.OneToOneField(Site) #ForeignKey(Site, default = Site.objects.get_current(), blank = True, null = True)
        
    template = models.CharField (default='default',max_length=255, choices=get_template_names_available()  )
        
    backup = models.OneToOneField (BackupCfg, help_text = 'Configuración de backup del site')
    
    category_img = models.ForeignKey(ImgCfg, default=ImgCfg())
    
    upload_dir =  models.CharField ( default='uploads', max_length = 256 )
    
    items_per_page =  models.PositiveSmallIntegerField( default=6, blank=False, help_text='Items per page')
    
    sharers = models.ManyToManyField ( SocialCfg )
    
    def __unicode__(self):
        return u'%s : %s' % ( self.site, self.title )
    
    def _get_template_name (self):
        return str(self.template)
    
    def _get_template_dir(self):
#        return TEMPLATES_ROOT + self.template_name
        return str (self.template)
    
    def get_keywords(self,max_keyw=10):
        abst = ""
        if (self.abstract):
            abst = self.abstract
        tit=""
        if (self.title):
            tit = self.title
        subtit = ""
        if (self.subtitle):
            subtit = self.subtitle  
        return get_keywords_text(get_keywords_text(abst,max_keyw) + ' ' + get_keywords_text(tit + " " + subtit,max_keyw), max_keyw)
    
    def get_base_url (self):
        return self.site.domain
    
    @staticmethod
    def current_cfg():
        try:
            site_id = Site.objects.get_current().id
            cfg_readed = SiteCfg.objects.get( site = site_id )
            return cfg_readed
        except:
            return SiteCfg()
    
    @staticmethod
    def get_template_dir():
        try:
            return str (SiteCfg.current_cfg().template)
        except ObjectDoesNotExist:
            return str (SiteCfg().template)
            
#        return TEMPLATES_ROOT + template_name
        
    template_name = property( _get_template_name )
    template_dir = property( _get_template_dir )
#    template_path = property( _get_template_path )


